package Communication;

/**
 *
 * @author mgrutman
 */
public class hostPacket 
{


/**
 * MF packet
 * - TAG 8 bytes "IPCON"
 * - LEN 4 integer with length of data
 * - ID  128 bytes of of some id
 * - Data [LEN] data length LEN
 * 
 * @author mgrutman
 */

    private static String tag;
    private static String id;
    public static byte[] packet = null;
    public static int packetIndex;

    public hostPacket()
    {
    }

    public static void setPacket (String tag, String id)
    {
        hostPacket.tag = tag;
        hostPacket.id = id;
    }
    
    /**
     * 
     * @return array of bytes that can be write into a socket
     */
    public static byte[] toBytes(byte buf[], int length)
    {
        int i;
        byte resBuf[] = new byte[1000];        
        byte tBuf[] = new byte[200];
        i = 0;

        // Put tag in array
        tBuf = tag.getBytes();
        int tag_len = Math.min(8, tag.length());

        for (int j = 0; j < tag_len; j++)
        {
            resBuf[i++] = tBuf[j];
        }
        // fill the rest with zeros
        for (int j = tag_len; j < 8; j++)
        {
            resBuf[i++] = 0;
        }

        // Put length in array
        byte len_byte [] = intToByteArray(length);
        for (int j = 0; j < 4; ++j)
            resBuf [i++] = len_byte [j];
        
        // Put id in array
        tBuf = id.getBytes();
        int id_len = Math.min(128, id.length());

        for (int j = 0; j < id_len; j++)
        {
            resBuf[i++] = tBuf[j];
        }
        // fill the rest with zeros
        for (int j = id_len; j < 128; j++)
        {
            resBuf[i++] = 0;
        }

        // Put Data in array
        for (int j = 0; j < length; ++j)
        {
            resBuf[i++] = buf[j];
        }
        
        return resBuf;
    }

    public static final byte[] intToByteArray(int value)
    {
        return new byte[]
            {
                (byte) (value >>> 24),
                (byte) (value >>> 16),
                (byte) (value >>> 8),
                (byte) value
            };
    }

    public static final int byteArrayToInt(byte[] b)
    {
        return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF);
    }
    
    public static byte[] stringToByteArray (String str)
    {
        byte resBuf [] = str.getBytes();

        return resBuf;
    }

    public static void newPacket ()
    {
        packet = new byte [1000];
        packetIndex = 0;
    }
    
    public static void PacketAddZeros (int num)
    {
        for (int i = 0; i < num; i++)
            packet[packetIndex++] = 0;
    }
    
    public static void PacketAddBuf (byte[] b, int len)
    {
        for (int i = 0; i < len; i++)
        {
            packet[packetIndex++] = b[i];             
        }
    }
    
    public static byte[] getPacket()
    {
        return packet;
    }
    
    public static int getPacketSize()
    {
        return packetIndex;
    }
    
}
